package bb.lanxing.activity.routebook;

import static bb.lanxing.common.config.Constants.RESULT_CODE_LUSHU_EDIT;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.mikephil.charting.utils.Utils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.adapter.RouteBookNormalAdapter;
import bb.lanxing.manager.LevelPermissionMgr;
import bb.lanxing.model.database.LevelHP;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.json.level.RuleConsume;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.Log;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.view.BiciAlertDialogBuilder;
import okhttp3.Request;
import okhttp3.Response;

public class RouteBookSearchResultActivity extends BaseActivity {
    private final static String TAG = "LushuSearchResultActivity";
    private static final int SEARCH_TYPE_DEFAULT = 0;
    private static final int SEARCH_TYPE_LUSHU_ID = 1;
    private static final int SEARCH_TYPE_ADDRESS = 2;
    private int SearchStyle;
    private RouteBookNormalAdapter adapter;
    private View emptyBackground;
    private double endLat;
    private double endLng;
    private String keyword;
    private ListView listView;
    private SwipeRefreshLayout refreshView;
    private double startLat;
    private double startLng;
    private int page = 0;
    private final int LIMIT = 20;
    private List<RouteBook> routeBookList = new ArrayList<>();

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_lushu_search_result);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        setTitle(R.string.title_activity_lushu_search);
        int intExtra = getIntent().getIntExtra("style", SEARCH_TYPE_DEFAULT);
        this.SearchStyle = intExtra;
        if (intExtra == SEARCH_TYPE_LUSHU_ID) {
            this.keyword = getIntent().getStringExtra("keyword");
        } else if (intExtra == SEARCH_TYPE_ADDRESS) {
            this.startLat = getIntent().getDoubleExtra("startLat", Utils.DOUBLE_EPSILON);
            this.startLng = getIntent().getDoubleExtra("startLng", Utils.DOUBLE_EPSILON);
            this.endLat = getIntent().getDoubleExtra("endLat", Utils.DOUBLE_EPSILON);
            this.endLng = getIntent().getDoubleExtra("endLng", Utils.DOUBLE_EPSILON);
            Log.d(TAG, this.startLat + "," + this.startLng + "," + this.endLat + "," + this.endLng);
        }
        this.adapter = new RouteBookNormalAdapter(this, this.routeBookList);
        // lushuNormalAdapter.setFragmentType(TYPE_SEARCH);
        this.adapter.setOnLoadEndListener(() -> {
            if (SearchStyle == SEARCH_TYPE_LUSHU_ID) {
                requestSearchLushu(false);
            } else if (SearchStyle == SEARCH_TYPE_ADDRESS) {
                requestSearchLushuByPosition(false);
            }
        });
        this.listView.setAdapter(this.adapter);
        this.listView.setOnItemClickListener((adapterView, view, i, j) -> {
            RouteBook routeBook = routeBookList.get((int) j);
            if (checkPermisstion()) {
                downloadAndTurnToDetail(routeBook);
            } else {
                showPermissionDialog(routeBook);
            }
        });
        refreshView.setOnRefreshListener(this::requestData);
        autoRefresh();
    }

    private void requestData() {
        if (SearchStyle == SEARCH_TYPE_LUSHU_ID) {
            requestSearchLushu(true);
        } else {
            requestSearchLushuByPosition(true);
        }
    }

    public void downloadAndTurnToDetail(RouteBook routeBook) {
        if (routeBook.getServerType() == 2 && routeBook.getId() == null) {
            downloadLushuWithCheck(routeBook);
        } else {
            startActivity(routeBook);
        }
    }

    private void autoRefresh() {
        requestData();
    }

    public void refreshComplete() {
        this.adapter.setLoadingMoreFinished();
        runOnUiThread(() -> {
            if (refreshView != null) {
                refreshView.setRefreshing(false);
            }
        });
    }

    private void startActivity(RouteBook routeBook) {
        Intent intent;
        if (routeBook.getServerType() == 2) {
            intent = new Intent(this, RouteBookDetailMapActivity.class);
            intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getId());
        } else {
            intent = new Intent(this, RouteBookInfoActivity.class);
            intent.putExtra("search_click", true);
            RouteBook routeBook2 = new RouteBook();
            routeBook2.setId(routeBook.getId());
            routeBook2.setServerId(routeBook.getServerId());
            routeBook2.setTitle(routeBook.getTitle());
            routeBook2.setUuid(routeBook.getUuid());
            intent.putExtra("lushu", (Parcelable) routeBook2);
        }
        startActivityForResult(intent, 76);
    }

    public void requestSearchLushu(final boolean z) {
        if (z) {
            this.page = 0;
        }
        MyHttpClient.searchLushu(new BiCiCallback(this) {
            @Override
            public void onFailure(Request request, IOException iOException) {
                super.onFailure(request, iOException);
                refreshComplete();
            }

            @Override
            public void onResponseString(@NonNull String str) {
                ArrayList<RouteBook> arrayList = new ArrayList<>();
                try {
                    JSONObject obj = new JSONObject(str);
                    JSONArray jSONArray = obj.getJSONArray("rows");
                    if (jSONArray.length() < LIMIT) {
                        adapter.setLoadMoreEnabled(false);
                    } else {
                        page++;
                        adapter.setLoadMoreEnabled(true);
                    }
                    for (int i = 0; i < jSONArray.length(); i++) {
                        arrayList.add(RouteBook.parseLushuByServer(jSONArray.getJSONObject(i), false));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                updateData(arrayList, z);
                refreshComplete();
            }
        }, this.keyword, SEARCH_TYPE_DEFAULT, this.page, this.LIMIT);
    }

    public void requestSearchLushuByPosition(final boolean z) {
        int i;
        if (z) {
            this.page = 0;
        }
        double d = this.startLat;
        if (d > Utils.DOUBLE_EPSILON && this.startLng > Utils.DOUBLE_EPSILON && this.endLat > Utils.DOUBLE_EPSILON
                && this.endLng > Utils.DOUBLE_EPSILON) {
            i = 6;
        } else if (d <= Utils.DOUBLE_EPSILON || this.startLng <= Utils.DOUBLE_EPSILON) {
            i = (this.endLat <= Utils.DOUBLE_EPSILON || this.endLng <= Utils.DOUBLE_EPSILON) ? 0 : 5;
        } else {
            i = 4;
        }
        MyHttpClient.searchLushuByStartEndPosition(new BiCiCallback(this) {
            @Override
            public void onFailure(Request request, IOException iOException) {
                super.onFailure(request, iOException);
                refreshComplete();
            }

            @Override
            public void onResponseString(@NonNull String str) {
                ArrayList<RouteBook> arrayList = new ArrayList<>();
                try {
                    JSONObject obj = new JSONObject(str);
                    JSONArray jSONArray = obj.getJSONArray("rows");
                    if (jSONArray.length() < LIMIT) {
                        adapter.setLoadMoreEnabled(false);
                    } else {
                        page++;
                        adapter.setLoadMoreEnabled(true);
                    }
                    for (int i2 = 0; i2 < jSONArray.length(); i2++) {
                        arrayList.add(RouteBook.parseLushuByServer(jSONArray.getJSONObject(i2), false));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                updateData(arrayList, z);
                refreshComplete();
            }
        }, i, this.startLat, this.startLng, this.endLat, this.endLng, this.page, this.LIMIT);
    }

    public void updateData(final List<RouteBook> list, final boolean clear) {
        if (list == null) {
            return;
        }
        runOnUiThread(() -> {
            if (adapter != null) {
                if (clear) {
                    routeBookList.clear();
                }
                routeBookList.addAll(list);
                adapter.notifyDataSetChanged();
                if (list.isEmpty()) {
                    emptyBackground.setVisibility(View.VISIBLE);
                } else {
                    emptyBackground.setVisibility(View.GONE);
                }
            }
        });
    }

    private void downloadLushuWithCheck(RouteBook routeBook) {
        if (routeBook.isExport() || LevelPermissionMgr.getInstance().checkPermission(1)) {
            downloadRouteBook(routeBook, false);
        } else {
            showCreditsDialog(routeBook);
        }
    }

    public void downloadRouteBook(final RouteBook routeBook, final boolean z) {
        showMyProgressDialog(R.string.dialog_downloading);
        routeBook.setSourceType(RouteBook.TYPE_DRAW);
        MyHttpClient.downloadRouteBook(new BiCiCallback() {
            String requestUrl = null;

            @Override
            public void onResponse(Response response) throws IOException {
                this.requestUrl = response.request().url().toString();
                super.onResponse(response);
            }

            @Override
            public void onResponseString(@NonNull String str) throws JSONException {
                // if (this.requestUrl.toLowerCase().endsWith(DeepLinkPathConstants.FILE_SUFFIX_GPX) ||
                // this.requestUrl.toLowerCase().endsWith(".gpxtest")) {
                // LushuUtil.parseGpxFile(str, lushu);
                // } else if (this.requestUrl.toLowerCase().endsWith(".json") ||
                // this.requestUrl.toLowerCase().endsWith(".jsontest")) {
                RouteBookUtil.parseDirectionNew(str, null, routeBook, routeBook.getSourceType());
                // } else {
                // LushuUtil.parseGpxFile(str, lushu);
                // }
                dismissLoadingDialog();
                setResult(RESULT_CODE_LUSHU_EDIT);
                processPermissionResponse(routeBook, z);
                App.getContext().sendBroadcast(new Intent(RouteBook.ACTION_DOWNLOAD_LUSHU));
            }
        }, routeBook.getServerType(), routeBook.getServerId());
    }

    public void processPermissionResponse(RouteBook routeBook, boolean z) {
        LevelHP levelHP;
        RuleConsume ruleConsume;
        if (routeBook != null && routeBook.getId() != null) {
            String string = getString(R.string.mine_level_toast_export_to_lushu_successful);
            if (z) {
                ruleConsume = LevelPermissionMgr.getInstance().getRule().getRuleConsume();
                if (ruleConsume != null) {
                    string = string
                            + getString(R.string.mine_level_toast_consume_credits, ruleConsume.getWorkoutExport());
                }
            } else {
                if (!routeBook.isExport()) {
                    LevelPermissionMgr.getInstance().updatePermisstion(1);
                }
                levelHP = LevelPermissionMgr.getInstance().getLevelHP();
                if (levelHP != null) {
                    string = string + getString(R.string.mine_level_toast_consume_count, levelHP.getWorkoutExport());
                }
            }
            App.getContext().showMessage(string);
            startActivity(routeBook);
            return;
        }
        App.getContext().showMessage(R.string.mine_level_toast_export_to_lushu_failed);
    }

    public void showCreditsDialog(final RouteBook routeBook) {
        new BiciAlertDialogBuilder(this).setMessage("当日免费转路书已超过次数限制，是否花费10积分下载？")
                .setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> downloadRouteBook(routeBook, true))
                .setNegativeButton(R.string.dialog_btn_cancel, null).show();
    }

    public boolean checkPermisstion() {
        return RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getStoragePermissions());
    }

    public void showPermissionDialog(final RouteBook routeBook) {
        new BiciAlertDialogBuilder(this).setTitle(getString(R.string.permission_request_permission_tips))
                .setMessage(getResources().getString(R.string.permission_lushu_need_storage)).setCancelable(true)
                .setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> requestPermission(routeBook))
                .setNegativeButton(R.string.skip, (dialogInterface, i) -> {
                }).create().show();
    }

    public void requestPermission(final RouteBook routeBook) {
        RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getStoragePermissions())
                .permissionRequestEachCombined(this, new RxPermissionUtil.PermissionCallBack() {
                    @Override
                    public void deny() {
                    }

                    @Override
                    public void granted() {
                        downloadAndTurnToDetail(routeBook);
                    }
                });
    }

    private void bindView(View view) {
        this.listView = view.findViewById(R.id.listView);
        this.refreshView = view.findViewById(R.id.refreshView);
        this.emptyBackground = view.findViewById(R.id.emptyBackground);
    }
}
